package com.whl.org.service.impl;

import com.whl.basic.exception.BusinessException;
import com.whl.basic.service.impl.BaseServiceImpl;
import com.whl.basic.util.BaiduAuditUtils;
import com.whl.basic.util.MD5Utils;
import com.whl.basic.util.StrUtils;
import com.whl.org.domain.Employee;
import com.whl.org.domain.Shop;
import com.whl.org.domain.ShopAuditLog;
import com.whl.org.dto.ShopDto;
import com.whl.org.mapper.EmployeeMapper;
import com.whl.org.mapper.ShopAuditLogMapper;
import com.whl.org.mapper.ShopMapper;
import com.whl.org.service.IShopService;
import com.whl.user.domain.Logininfo;
import com.whl.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 店铺业务实现类
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper ShopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    public void settlement(Shop shop) {
        // 一：校验
        // 1.控制校验
        if(StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getAddress()) || StringUtils.isEmpty(shop.getTel())
        || StringUtils.isEmpty(shop.getEmployee().getUsername()) || StringUtils.isEmpty(shop.getEmployee().getEmail())
        || StringUtils.isEmpty(shop.getEmployee().getPassword()) || StringUtils.isEmpty(shop.getEmployee().getPhone())){
            throw new BusinessException("数据不能为空");
        }
        // 2.密码是否一致
        // 3.校验店铺名称是否合规
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
        if(!boo){
            throw new BusinessException("店铺名称不合规，请重新输入!!!");
        }
        // 4.是否曾经入驻过
        Shop shoptemp = ShopMapper.loadByMessage(shop);
        if(shoptemp != null){
            throw new BusinessException("已经入驻过，请直接登录！忘记密码请找回密码!!");
        }
        // 二：添加到数据库
        // 1.添加管理员信息到employee
        Employee employee = shop.getEmployee();
        // 处理盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 调用md5工具类，给密码加密加盐
        String md5Password = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Password);
        // 保存员工信息employee
        employeeMapper.save(employee);
        // 2.保存店铺信息shop
        shop.setAdmin_id(employee.getId());
        ShopMapper.save(shop);
        // 3.保存登录信息logininfo
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        // 4.将店铺信息更新到emplyee中
        employee.setShop_id(shop.getId());
        // 5.将登录信息更新到employee
        employee.setLogininfo_id(logininfo.getId());
        // 6.修改员工信息 - 修改Shop_id和Logininfo_id
        employeeMapper.update(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        // 按照同名属性赋值
        BeanUtils.copyProperties(employee,logininfo);
        // 当前对象是店铺管理员
        logininfo.setType(0);
        return logininfo;

    }

    /**
     *  店铺审核通过
     * @param shopAuditLog
     */
    @Override
    public void pass(ShopAuditLog shopAuditLog) throws MessagingException {
        // 1.修改店铺状态
        // 根据日志ID查找到shop对象
        Shop shop = ShopMapper.findOne(shopAuditLog.getShopId());
        // 修改店铺状态
        shop.setState(2);
        // 更新到数据库
        ShopMapper.update(shop);
        // 2.添加审核日志到数据库
        shopAuditLog.setAuditId(1L);
        shopAuditLog.setState(2);
        shopAuditLogMapper.save(shopAuditLog);
        // 3.发送邮件
        // 复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom("2537809423@qq.com");
        // 设置邮件主题
        helper.setSubject("审核通过邮件");
        // 设置邮件正文
        helper.setText("<h1>你的店铺已经注册!!!</h1>" +
                "<img src='http://123.207.27.208:80"+shop.getLogo()+"' >" +
//                "<a href='http://localhost:8081/shop/active/"+shop.getId()+"'>点击该链接激活</a>",true);
                "<a href='http://172.16.10.45:8081/#/active/?"+shop.getId()+"'>点击该链接激活</a>",true);
        // 设置收件人
        Employee employee = employeeMapper.findOne(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("2537809423@qq.com");
        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    /**
     * 店铺审核驳回
     * @param shopAuditLog
     * @throws MessagingException
     */
    @Override
    public void reject(ShopAuditLog shopAuditLog) throws MessagingException {
        // 1.修改店铺状态
        // 根据日志ID查找到shop对象
        Shop shop = ShopMapper.findOne(shopAuditLog.getShopId());
        // 2.添加审核日志到数据库
        shopAuditLog.setAuditId(1L);
        shopAuditLog.setState(4);
        shopAuditLogMapper.save(shopAuditLog);
        // 3.发送邮件
        // 创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom("2537809423@qq.com");
        // 设置邮件主题
        helper.setSubject("审核驳回邮件");
        // 设置邮件正文
        helper.setText("<h1>入驻失败!!!</h1>" +
                "<a href='http://localhost:8081/register'>点击重新入驻</a>",true);
        // 设置收件人
        Employee employee = employeeMapper.findOne(shop.getAdmin_id());
        helper.setTo(employee.getEmail());
        //helper.setTo("3049903126@qq.com");
        // 发送邮件
        javaMailSender.send(mimeMessage);
        // 4.删除入驻信息
        // 删除管理员信息
        employeeMapper.delete(shop.getAdmin_id());
        // 删除店铺信息
        ShopMapper.delete(shop.getId());
    }

    /**
     * 获取所有状态的数量
     * @return
     */
    @Override
    public List<ShopDto> getCountByState() {
        return ShopMapper.getCountByState();
    }

    /**
     * 店铺激活
     * @param id 店铺编号
     */
    @Override
    public void shopActive(Long id) {
        // 查询需要成功激活的店铺信息
        Shop shop = ShopMapper.findOne(id);
        // 修改店铺状态
        shop.setState(3);
        // 操作数据库，修改店铺状态
        ShopMapper.update(shop);
    }
}
